<template>
  <div class="position-wrap">
    <div
      ref="item"
      v-if="isShow"
      class="position-item"
      v-transfer-dom
      :data-transfer="showItem"
      :style="{left: itemX+'px', top: itemY+'px'}"
      v-clickOUtSide="close"
    >
      <slot></slot>
  </div>
  </div>
</template>
<script>
import transferDom from '@/directives/transfer-dom';
import clickOUtSide from '@/directives/click-out';
export default {
	props: {
		top: Boolean,
		right: Boolean,
		bottom: Boolean,
		left: Boolean,
		open: {
			type: Boolean,
			default: true,
		},
	},
	directives: { transferDom, clickOUtSide },
	data() {
		return {
			elX: 0,
			elY: 0,
			itemHeight: 0,
			itemWidth: 0,
			elHeight: 0,
			elWidth: 0,
			showItem: true,
			isShow: false,
		};
	},
	computed: {
		itemX() {
			if (this.isShow) {
				if (this.top) {
					return this.elX;
				}
				if (this.bottom) {
					return this.elX;
				}
				if (this.left) {
					return this.elX - this.itemWidth;
				}
				if (this.right) {
					return this.elX + this.elWidth;
				}
			}
		},
		itemY() {
			if (this.isShow) {
				if (this.top) {
					return this.elY - this.itemHeight;
				}
				if (this.bottom) {
					return this.elY;
				}
				if (this.left) {
					return this.elY;
				}
				if (this.right) {
					return this.elY;
				}
			}
		},
	},
	methods: {
		getElPosition() {
			let obj = this.$el;
			let left = obj.offsetLeft;
			let top = obj.offsetTop;
			let width = 0;
			let parent = obj.parentNode;
			while (parent.tagName !== 'BODY') {
				if (parent.offsetWidth && !width) {
					width = parent.offsetWidth;
				}
				left += parent.offsetLeft;
				top += parent.offsetTop;
				parent = parent.parentNode;
			}
			left += width;
			this.elX = left;
			top = top - 50;
			let clientHeight =
				window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			if (top + this.$refs.item.offsetHeight > clientHeight) {
				top = clientHeight - this.$refs.item.offsetHeight;
			}
			this.elY = top > 0 ? top : 0;
		},
		getSize() {
			this.itemHeight = this.$refs.item.offsetHeight;
			this.itemWidth = this.$refs.item.offsetWidth;
			this.elHeight = this.$el.offsetHeight;
			this.elWidth = this.$el.offsetWidth;
		},
		close() {
			this.isShow = false;
		},
	},
	mounted() {
		if (!this.open) return;
		setTimeout(() => {
			this.isShow = true;
			this.$nextTick(() => {
				this.getElPosition();
				this.getSize();
			});
		}, 100);
	},
	destoryed() {
		this.isShow = false;
	},
};
</script>
<style lang="less">
.position-item {
	position: absolute;
	z-index: 100;
	background: #363e4f;
	.menu-title {
		padding: 15px 4px;
		padding-left: 16px;
		color: #fff;
		font-size: 13px;
	}
	.ivu-menu-item {
		margin-left: -23px;
		padding: 8px 10px;
		padding-right: 24px;
		font-size: 13px;
		color: hsla(0, 0%, 100%, 0.7);
		&.menu-item-selected {
			color: #fff;
			background-color: #2d8cf0;
		}
	}
}
</style>
